import { useState, useEffect } from 'react';
import { RotateCcw, ZoomIn, ZoomOut, X, Image as ImageIcon, FileText, Upload, ChevronDown } from 'lucide-react';
import ProgressBar from './ProgressBar';

interface File {
  id: number;
  name: string;
  type: 'image' | 'pdf';
  size: string;
  date: string;
  url?: string;
  savedPath?: string;
  file?: Blob; // 修改为Blob类型
}

interface PreviewAreaProps {
  file: File | null;
  isRecognizing: boolean;
  progress: number;
  onReRecognize: () => void;
  onSwitchToUploadView: () => void;
}

export default function PreviewArea({ file, isRecognizing, progress, onReRecognize, onSwitchToUploadView }: PreviewAreaProps) {
  const [zoomLevel, setZoomLevel] = useState(100);
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const [imageLoading, setImageLoading] = useState(false);
  const [imageError, setImageError] = useState(false);
  const [pdfUrl, setPdfUrl] = useState<string | null>(null);
  const [selectedModel, setSelectedModel] = useState('paddleocr');
  const [modelOptions, setModelOptions] = useState<Array<{id: string, name: string}>>([
    { id: 'paddleocr', name: 'PaddleOCR' }
  ]);
  const [isModelDropdownOpen, setIsModelDropdownOpen] = useState(false);

  // 加载模型配置
  useEffect(() => {
    const loadModelConfigs = () => {
      const savedConfigs = localStorage.getItem('modelConfigs');
      const savedStatus = localStorage.getItem('modelStatus');
      const configs = savedConfigs ? JSON.parse(savedConfigs) : null;
      const status = savedStatus ? JSON.parse(savedStatus) : null;
      
      if (configs && status) {
        const models = [{ id: 'paddleocr', name: 'PaddleOCR' }];
        
        // 添加启用的VLM模型
        Object.keys(status).forEach(modelId => {
          if (status[modelId] && configs[modelId]) {
            models.push({ 
              id: modelId, 
              name: configs[modelId].name || modelId 
            });
          }
        });
        
        setModelOptions(models);
      }
    };
    
    loadModelConfigs();
    
    // 监听localStorage变化
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'modelConfigs' || e.key === 'modelStatus') {
        loadModelConfigs();
      }
    };
    
    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);
  
  const handleZoomIn = () => {
    setZoomLevel(prev => Math.min(prev + 10, 200));
  };
  
  const handleZoomOut = () => {
    setZoomLevel(prev => Math.max(prev - 10, 50));
  };
  
  // Reset zoom when file changes
  useEffect(() => {
    if (file && file.type === 'image') {
      setImageLoading(true);
      setImageError(false);
      
      // 如果文件有URL，则直接使用该URL显示图片
      if (file.url) {
        setImageUrl(file.url);
        setImageLoading(false);
      } else {
        // 如果没有URL，则使用占位图片
        const timer = setTimeout(() => {
          setImageUrl(`https://picsum.photos/600/800?random=${file?.id}`);
          setImageLoading(false);
        }, 500);
        
        return () => clearTimeout(timer);
      }
    } else if (file && file.type === 'pdf') {
      // 处理PDF文件
      if (file.url) {
        setPdfUrl(file.url);
      } else if (file.file) {
        // 为PDF文件创建对象URL
        const url = URL.createObjectURL(file.file);
        setPdfUrl(url);
        return () => URL.revokeObjectURL(url);
      }
    } else {
      setImageUrl(null);
      setPdfUrl(null);
      setImageLoading(false);
      setImageError(false);
    }
    
    // Reset zoom level
    setZoomLevel(100);
  }, [file]);
  
  if (!file) {
    return (
      <div className="flex-1 flex items-center justify-center text-center p-8">
        <div className="bg-gray-100 p-6 rounded-full mb-4 inline-block">
          <ImageIcon className="w-12 h-12 text-gray-400" />
        </div>
        <h3 className="text-lg font-medium text-gray-700 mb-1">未选择文件</h3>
        <p className="text-gray-500 max-w-md">请从左侧文件列表中选择一个文件进行预览</p>
      </div>
    );
  }
  
  return (
    <div className="flex flex-col h-full">
      {/* 文件信息栏 */}
      <div className="border-b border-gray-200 p-4 flex items-center justify-between">
        <div className="flex items-center">
          {file.type === 'pdf' ? (
            <FileText className="w-5 h-5 mr-2 text-gray-500" />
          ) : (
            <ImageIcon className="w-5 h-5 mr-2 text-gray-500" />
          )}
          <div>
            <h3 className="text-sm font-medium text-gray-800 truncate max-w-xs">{file.name}</h3>
            <p className="text-xs text-gray-500">{file.size} · {file.date}</p>
            {file.savedPath && (
              <p className="text-xs text-gray-400 truncate max-w-xs">保存路径: {file.savedPath}</p>
            )}
          </div>
        </div>
        
        <div className="flex items-center space-x-2">
          <button 
            className="p-1.5 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded"
            onClick={handleZoomOut}
          >
            <ZoomOut className="w-4 h-4" />
          </button>
          <span className="text-xs text-gray-500 w-10 text-center">{zoomLevel}%</span>
          <button 
            className="p-1.5 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded"
            onClick={handleZoomIn}
          >
            <ZoomIn className="w-4 h-4" />
          </button>
        </div>
      </div>
      
      {/* 预览区域 */}
      <div className="flex-1 overflow-hidden relative bg-gray-100">
        <div 
          className="absolute inset-0 flex items-center justify-center p-4 transform transition-transform duration-300 ease-out"
          style={{ transform: `scale(${zoomLevel / 100})` }}
        >
          <div className="bg-white shadow-md max-w-full max-h-full overflow-auto">
            {file.type === 'image' ? (
              <>
                {imageError ? (
                  <div className="bg-gray-200 w-[600px] h-[800px] relative flex items-center justify-center">
                    <div className="text-center p-8">
                      <X className="w-16 h-16 mx-auto mb-4 text-red-300" />
                      <p className="text-red-500">图片加载失败</p>
                      <p className="text-sm text-gray-500 mt-2">{file.name}</p>
                      <button 
                        className="mt-4 px-4 py-2 bg-red-100 text-red-600 rounded text-sm"
                        onClick={() => {
                          setImageError(false);
                          // In a real app, you would re-try loading the image or select a new file
                        }}
                      >
                        重试
                      </button>
                    </div>
                  </div>
                ) : imageLoading ? (
                  <div className="bg-gray-200 w-[600px] h-[800px] relative flex items-center justify-center">
                    <div className="text-center p-8">
                      <div className="w-16 h-16 mx-auto mb-4 border-4 border-gray-300 border-t-blue-500 rounded-full animate-spin"></div>
                      <p className="text-gray-400">图片加载中...</p>
                      <p className="text-sm text-gray-500 mt-2">{file.name}</p>
                    </div>
                  </div>
                ) : imageUrl ? (
                  <img 
                    src={imageUrl} 
                    alt={file.name}
                    className="max-w-full max-h-full object-contain"
                    style={{ minWidth: '200px', minHeight: '200px' }}
                    onError={() => setImageError(true)}
                  />
                ) : (
                  <div className="bg-gray-200 w-[600px] h-[800px] relative flex items-center justify-center">
                    <div className="text-center p-8">
                      <ImageIcon className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                      <p className="text-gray-400">图片预览</p>
                      <p className="text-sm text-gray-500 mt-2">{file.name}</p>
                    </div>
                  </div>
                )}
              </>
            ) : (
              <div className="w-[600px] h-[800px] flex flex-col">
                {pdfUrl ? (
                  <iframe
                    src={pdfUrl}
                    className="w-full h-full border-0"
                    title={`PDF Preview - ${file.name}`}
                    onError={() => setPdfUrl(null)}
                  />
                ) : (
                  <div className="bg-gray-200 w-full h-full flex items-center justify-center">
                    <div className="text-center p-8">
                      <FileText className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                      <p className="text-gray-400">PDF文件预览</p>
                      <p className="text-sm text-gray-500 mt-2">{file.name}</p>
                      <p className="text-xs text-gray-500 mt-2">无法生成预览，请确保文件格式正确</p>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
      
      {/* 底部操作栏 */}
      <div className="border-t border-gray-200 p-4 bg-white">
        {isRecognizing ? (
          <div>
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium text-gray-700">正在识别...</span>
              <span className="text-sm text-gray-500">{Math.round(progress)}%</span>
            </div>
            <ProgressBar progress={progress} className="h-2" />
          </div>
        ) : (
          <div className="flex space-x-2">
            <div className="flex-1 flex">
              <button 
                className="flex-1 flex items-center justify-center py-2 px-4 bg-blue-600 text-white rounded-l-lg text-sm font-medium hover:bg-blue-700 transition"
                onClick={() => onReRecognize && onReRecognize(selectedModel)}
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新识别
              </button>
              <div className="relative">
                <button 
                  className="flex items-center justify-between py-2 px-3 bg-blue-700 text-white rounded-r-lg text-sm font-medium hover:bg-blue-800 transition min-w-[120px]"
                  onClick={() => setIsModelDropdownOpen(!isModelDropdownOpen)}
                >
                  <span className="mr-2">
                    {modelOptions.find(option => option.id === selectedModel)?.name || '选择模型'}
                  </span>
                  <ChevronDown className="w-4 h-4" />
                </button>
                
                {isModelDropdownOpen && (
                  <div className="absolute bottom-full right-0 mb-1 w-full bg-white rounded-lg shadow-lg border border-gray-200 z-10">
                    {modelOptions.map((option) => (
                      <button
                        key={option.id}
                        className={`w-full text-left px-4 py-2 text-sm ${selectedModel === option.id ? 'bg-blue-100 text-blue-700' : 'text-gray-700 hover:bg-gray-100'}`}
                        onClick={() => {
                          setSelectedModel(option.id);
                          setIsModelDropdownOpen(false);
                        }}
                      >
                        {option.name}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
            <button 
              className="flex-1 flex items-center justify-center py-2 px-4 bg-gray-600 text-white rounded-lg text-sm font-medium hover:bg-gray-700 transition"
            >
              <FileText className="w-4 h-4 mr-2" />
              查看结果
            </button>
            <button 
              className="flex-1 flex items-center justify-center py-2 px-4 bg-green-600 text-white rounded-lg text-sm font-medium hover:bg-green-700 transition"
              onClick={onSwitchToUploadView}
            >
              <Upload className="w-4 h-4 mr-2" />
              上传新图片
            </button>
          </div>
        )}
      </div>
    </div>
  );
}